/*
 * DAC_Bsp.c
 *
 *  Created on: Dec 3, 2020
 *      Author: Administrator
 */


#include	"DAC_Bsp.h"
#include	"stdio.h"
#include	"dac.h"
#include	"tim.h"


ALIGN_32BYTES(__attribute__((section (".RAM_D2"))) uint16_t g_usDac1Buff[DAC_BUF_LEN]);
//volatile uint16_t g_usDac1Buff[DAC_BUF_LEN] __attribute__((at(0x30000000))) = { 1,2,3 };
//volatile uint16_t __attribute__((section (".RAM_D2"))) g_usDac1Buff[DAC_BUF_LEN];

typedef	enum	Wav_type
{
	WAV_SQUARE = 0,
	WAV_SIN = 1,
	WAV_TRIANGLE = 2,

}Wav_type_t;

Wav_type_t		g_dac_wav_type = WAV_SIN;	//WAV_TRIANGLE;
float			g_sin_amp_vpp = 1.0;
float			g_sin_base	= 1.65;
float			g_dac_vref = 3.3;
float			g_PI	= 3.1415926;

void	init_dac_buff(void)
{
	int16_t i;

	switch(g_dac_wav_type)
	{
		case WAV_TRIANGLE:
			{
				for(i=0;i<=DAC_BUF_LEN/2;i++)
				{
					g_usDac1Buff[i] = 2*i*DAC_MAX_VALUE/DAC_BUF_LEN;
				}
				for(i=1+DAC_BUF_LEN/2;i<DAC_BUF_LEN;i++)
				{
					g_usDac1Buff[i] = 2*(DAC_MAX_VALUE - i*DAC_MAX_VALUE/DAC_BUF_LEN);
				}
			}break;
		case WAV_SQUARE:
			{
				for(i=0;i<=DAC_BUF_LEN/2;i++)
				{
					g_usDac1Buff[i] = 0;
				}
				for(i=1+DAC_BUF_LEN/2;i<DAC_BUF_LEN;i++)
				{
					g_usDac1Buff[i] = DAC_MAX_VALUE;
				}
			}break;
		case WAV_SIN:
			{
				float	famp = g_sin_amp_vpp/g_dac_vref*DAC_MAX_VALUE/2;
				float	fbase = g_sin_base/g_dac_vref*DAC_MAX_VALUE;
				for(i=0;i<=DAC_BUF_LEN;i++)
				{
					g_usDac1Buff[i] = fbase + famp*sin(i*2*g_PI/DAC_BUF_LEN);
				}
			}
			break;
		default:
			break;
	}
}


void	dac_test(void)
{
	init_dac_buff();

	__HAL_TIM_ENABLE_DMA(&htim6,TIM_DMA_UPDATE);
	__HAL_TIM_ENABLE(&htim6);
	HAL_DAC_Start(&hdac1,DAC_CHANNEL_1 );
	HAL_DMA_Start_IT(&hdma_tim6_up,(uint32_t)g_usDac1Buff, (uint32_t)&DAC1->DHR12R1 , DAC_BUF_LEN);
	HAL_TIM_Base_Start_IT(&htim6);
	HAL_DAC_Start(&hdac1,DAC_CHANNEL_1 );

}



#define		DAC_SPAN		20



void 	dac_process(void)
{
	static	uint32_t	dac_stamp;
	static  uint16_t 	dac_val = 0;
	HAL_StatusTypeDef   hal_stat;
	if(HAL_GetTick()-dac_stamp >= DAC_SPAN)
	{
		dac_stamp = HAL_GetTick();
		hal_stat = HAL_DAC_SetValue(&hdac1, DAC_CHANNEL_1, DAC_ALIGN_12B_R, dac_val%4095);
		dac_val+=10;
		if(dac_stamp%500 == 0)
		{
			printf("dac_val:%d, hal_stat:%d\r\n", dac_val,hal_stat);
		}
		HAL_DAC_Start(&hdac1,DAC_CHANNEL_1 );
	}
}






